import BTControlNode from "../BTControlNode";
import { BTResult, FAILURE, RUNNING, SUCCESS } from "../BTEnum";
import BTNode from "../BTNode";

/**
 * 并行节点，只要有一个节点成功，就返回成功，所有节点都失败了，则返回失败
 */
export default class BTParallel extends BTControlNode {
    private _childrenResults: BTResult[];
    constructor(children: BTNode[]) {
        super(children);
        this._childrenResults = new Array(this.children.length);
    }

    start() {
        this._childrenResults.fill(RUNNING);
        for (let i = 0; i < this.children.length; i++) {
            this.children[i].start();
        }
    }

    update() {
        let succCount = 0, failureCount = 0;
        for (let i = 0; i < this.children.length; i++) {
            if (this._childrenResults[i] !== RUNNING) {
                this._childrenResults[i] === SUCCESS ? succCount++ : failureCount++;
            } else {
                this._childrenResults[i] = this.children[i].update();
                if (this._childrenResults[i] !== RUNNING) {
                    this.children[i].end();
                    this._childrenResults[i] === SUCCESS ? succCount++ : failureCount++;
                }
            }
        }

        return succCount === this.children.length ?
            SUCCESS :
            failureCount === this.children.length ? FAILURE : RUNNING;
    }

    end(): void {
        for (let i = 0; i < this.children.length; i++) {
            if (this._childrenResults[i] === RUNNING) {
                this.children[i].end();
            }
        }
    }
}
